package com.hfi.my;

import com.hfi.model.Employee;

import java.sql.*;

/**
 * @author ChangLiang
 * @date 2019/5/16
 */
public class MySimpleExecutor implements MyExecutor {

    @Override
    public <E> E query(String statement, Object parameter) {
        Connection conn = null;
        try {
            conn = getConection();
            PreparedStatement pstmt;
            pstmt = conn.prepareStatement(statement);
            pstmt.setInt(1,Integer.valueOf(String.valueOf(parameter)));
            ResultSet resultSet = pstmt.executeQuery();

            Employee employee = new Employee();
            while (resultSet.next()) {
                employee.setId(resultSet.getInt(1));
                employee.setLastName(resultSet.getString(2));
                employee.setGender(resultSet.getString(3));
                employee.setEmail(resultSet.getString(4));
            }
            return (E) employee;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private Connection getConection() throws ClassNotFoundException, SQLException {
        Connection connection = null;

        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mybatis_demo";
        String username = "root";
        String password = "1230456";
        Class.forName(driver);

        connection = DriverManager.getConnection(url, username, password);

        return connection;
    }
}
